<template>
	<view class="equipmentbg">
		<navbar name="体脂测量"></navbar>
		<view class="equipmenttz">
			<view class="buzhou-one">
				<text class="bz-text">步骤1</text>请先确认设备处于工作状态，并打开手机蓝牙功能
			</view>
			<view class="buzhou-one" style="top:555upx;">
				<text class="bz-text">步骤2</text>手机与设备连接成功后，请赤脚上秤进行测量
			</view>
			<view class="buzhou-one" style="top:1134upx;">
				<text class="bz-text">步骤3</text>测量结束后请耐心等待测量结果
			</view>
		</view>
	</view>
</template>

<script>
	// #ifdef MP-WEIXIN
	const QNBleApi = require("@/components/peripheral/qnble")
	import { init } from '@/sg/index'
	const {
		Report
	} = require("@/components/peripheral/index")
	// #endif
	export default {
		data() {
			return {
				Intervaltime:'',
				Interval:'',
				pages: '', //当前页面
				today: this.$basejs.thisdayFormat2(false), //记录时间
				deviceId: '',
				mac: '',
				age: 30,
				autoStopDiscovery: true,
				gender: "male",
				height: 170,
				isSport: false,
				unit: "kg",

				realTimeWeight: 0,
				bleState: "空闲",
				state: "paused",
				measureData: null,
				score: 0,
				available: false,
				discovering: false,
				connected: false,
				connecting: false,

				clockInOrNot: false, //是否通过打卡进入
			}
		},
		onLoad(e) {
			if (e.type == 1) {
				this.clockInOrNot = true
			} else {
				this.clockInOrNot = false
			}
			this.onLoadmethods();
			var pages = getCurrentPages();
			pages = pages.reverse();
			pages = pages[pages.length - 1].route //当前页面url
			this.pages = pages;
			// wx.showToast({
			// 	title: '请站上体脂称',
			// 	icon: 'none',
			// 	duration: 20000
			// })
			wx.showLoading({
				title: '搜索设备中...',
			})
		},
		onShow() {
		this.getUserInfoWidth();
		},
		mounted() {
			this.mountedmethods()
		},
		// 组件加载完毕
		updated() {
			// 调用搜索设备
		},
		// destroyed() {
		// 	// this.bleApi.stop()
		// 	this.bleApi.stop()
		// 		.then(() => {
		// 			this.connected = false
		// 		})
		// },
		onUnload() {
			clearInterval(this.Interval);
			clearInterval(this.Intervaltime);
			let _this = this;
			this.restart()

			init(global.userInfo.userId)
			// this.bleApi.stop()
			// 	.then(() => {
			// 		_this.connected =false
			// 	})
		},
		methods: {
			getUserInfoWidth(){
				let _this = this;
				this.$loginl.get(global.apiUrls.getUserInfoWidth, {})
					.then(res => {
						if(res.data.code == 1000){
							let result = res.data.result;
							if (result) {
								if(result.age == ''||result.height == ''||result.gender == ''){
									uni.hideToast();
									_this.Intervaltime = setTimeout((e)=>{
										uni.showToast({
										    title: '为了测量的准确性，请您完善身高，性别与年龄！',
											icon:'none',
										    duration: 5000
										});
									},1000)

									_this.Interval = setTimeout((e)=>{
										uni.navigateTo({
											url:'/pagesMy/my/record/record?type=perfect'
										})
									},5000)
								}else{
									if(result.age == '0'){
										result.age = '1'
									}
									_this.age = result.age;
									_this.autoStopDiscovery = result.autoStopDiscovery;
									_this.gender = result.gender;
									_this.height = result.height;
									_this.isSport = result.isSport;
									_this.measureMethod = result.measureMethod;
									_this.unit = result.unit;
								}

							}
						}
					})
			},
			mountedmethods() {
				const {
					autoStopDiscovery
				} = this
				this.bleApi.init({
						appId: "wx3581a642cd0e4a4d",
						secret: "42e4c5d4a8d52e5241b29022a7b9865c",
						autoStopDiscovery,
						logger: this.logger()
					})
					.then(bleEnableState => {
						console.log("当前蓝牙状态", bleEnableState)
						if (bleEnableState)
							wx.hideLoading();
						this.bleApi.startBleDeviceDiscovery()
					})
			},
			onLoadmethods() {


				//初始化蓝牙
				this.bleApi = new QNBleApi()

				this.bleApi.setDeviceEventListener(this);
				this.bleApi.setBleEventListener(this);

				wx.openBluetoothAdapter({
					mode: "peripheral",
					success: res => {
						wx.createBLEPeripheralServer({
							success: res => {
								//设置广播秤的蓝牙服务
								console.log("蓝牙状态变化，设置蓝牙服务")
								this.bleApi.setBleServer(res.server)
							}
						})
					}
				})
			},
			logger: () => {
				const wxlogger = wx.getLogManager && wx.getLogManager({
					level: 0,
				})
				const log = (...params) => {
					console.log(...params)
					wxlogger && wxlogger.log(...params)
				}
				return {
					log
				}
			},
			//事件回调
			restart() {
				let _this = this;
				this.bleApi.stop()
					.then(() => {
						console.log("停止扫描")
						_this.connected = false;
						_this.bleApi.startBleDeviceDiscovery()
					})
					.catch((err) => {
						console.log("停止扫描失败", err)
					})


			},

			//下面是蓝牙事件的相关回调
			//开始扫描的回调
			onInitSuccess(bleEnableState) {
				if (bleEnableState) {
					this.updateState("蓝牙可用")
				} else {
					this.updateState("蓝牙不可用")
				}
			},
			onStartDiscoveryDevice() {
				this.updateState("开始扫描")
				this.devices = []
				this.discovering = true
			},

			//结束扫描的回到
			onStopDiscoveryDevice() {
				this.updateState("已停止扫描")
				this.discovering = false
			},
			//回调扫描对象
			onBleDeviceFound(device) {
				const {
					height,
					age,
					gender,
					isSport,
					unit,
					connected,
				} = this;
				if (this.connecting || connected) {
					console.log("当前正在连接，不再处理")
					return
				}else{
					this.connecting = true
					const birthday = new Date()
					birthday.setFullYear(birthday.getFullYear() - age)
					const user = {
						height,
						age,
						gender,
						isSport,
						birthday,
					}
					this.bleApi.createBleConnection(device, {
						user,
						unit,

					})
				}
				// this.bleApi.stopBleDeviceDiscovery()
			},
			/**
			 * 正在进行连接设备，在调用连接设备后，会马上回调
			 */
			onConnecting(device) {
				wx.showLoading({
					title: '搜索设备中...',
				})
				// this.updateState("正在连接")
				this.connecting = true
				this.connected = false
			},
			/**
			 * 	设备已连接成功 会回调设备对象
			 */
			onConnected(device) {
				wx.hideLoading()
				this.updateState("已连接")
				console.log("设备已连接", device);
				this.connecting = false
				var pages = getCurrentPages();
				pages = pages.reverse();
				pages = pages[0].route //当前页面url
				// console.log(pages,'264444444444444444444444')
				if(pages == 'pages/subpackage/home/equipment/balance'){

					console.log('267777777777777777777777')
					this.connected = true;
				}
				this.state = "running";
				this.device = device
				this.deviceId = device.deviceId; //设备已连接
				this.mac = device.mac; //设备mac
				// device
			},

			onBluetoothEnableChange(bleEnableStatus) {
				if (bleEnableStatus) {
					this.updateState("蓝牙可用，空闲")
					wx.openBluetoothAdapter({
						mode: "peripheral",
						success: res => {
							wx.createBLEPeripheralServer({
								success: res => {
									//设置广播秤的蓝牙服务
									console.log("蓝牙状态变化，设置蓝牙服务")
									this.bleApi.setBleServer(res.server)
								}
							})
						}
					})
				} else {
					this.updateState("蓝牙不可用")
				}
				this.available = bleEnableStatus
			},


			/**
			 * 	设备的服务搜索完成，正常情况下会在 onConnected后面调用
			 */
			onDeviceReady(device) {
				this.updateState("设备已经就绪")
				console.log("设备已就绪", device);
			},

			/**
			 * 蓝牙断开了连接
			 */
			onDisconnected(device) {
				this.updateState("设备连接已断开")
				this.connected = false;
				this.state = "paused";
				this.connecting = false;
				this.searching = false;
				if (this.pages == 'pages/subpackage/home/equipment/balance') {
					// wx.showToast({
					// 	title: '设备连接已断开',
					// 	icon: 'none',
					// })
					wx.showModal({
						title: '提示',
						content: '设备连接已断开',
						showCancel: false,
						success: function(res) {
							// uni.navigateBack({
							// 	delta: 1
							// });
						}
					})
				}
				// console.log("设备连接已断开", device);
			},

			//下面是秤端相关事件回调
			onGetUnsteadyWeight(weight) {
				if(this.connected){
					wx.showLoading({
						title: '测量中...',
					})
					console.log("收到实时数据", weight);
					this.score = weight;
					this.realTimeWeight = weight
					// this.connected = true;
					this.state = "running";
				}else{
					console.log('回到当前页面 方可测量')
				}

			},
			// 存储电子秤数据
			// 电子秤获取体重
			balanceData(data) {
				uni.hideToast();
				var pages = getCurrentPages();
				pages = pages.reverse();
				pages = pages[0].route //当前页面url
				let equipmentData = JSON.parse(data.equipmentData);
				console.log(data,equipmentData,'3661111111111111111111111')
				if(pages == 'pages/subpackage/home/equipment/balance'&&equipmentData.weight >0){
					this.addRecord(data.equipmentData, data.mac, data.deviceId) //设备记录体重
					}
				// this.tbEquipmentData(data.deviceId, data.equipmentData, data.mac) //存储电子秤数据
			},
			// 记录体重设备
			addRecord(equipmentData, mac, deviceId) {
				// 获取身高
				equipmentData = JSON.parse(equipmentData);
				equipmentData.height = equipmentData.user.height;
				equipmentData = JSON.stringify(equipmentData)
				// end
				let _this = this,
					fdata = {
						deviceType: 'WEIGHT',
						recordTime: this.today,
						inputType: 2, //1手动 2设备
						userId: uni.getStorageSync(global.IS_DEV?'USER_DATA_BSY_T':'USER_DATA_BSY_Z').userId,
						mac: mac, //设备mac
						deviceId: deviceId, //设备id
						healthDataId: '',
						healthData: equipmentData,
					};
				this.$api.post(global.apiUrls.addRecord, fdata).then(res => {
					if (res.data.code == 1000) {
						// if (_this.pages == 'pages/subpackage/home/equipment/balance') {
							uni.showToast({
								title: res.data.message,
								duration: 2000
							});
							// 结果卸载电子秤
							// _this.bleApi.stop()
							// 	.then(() => {
							// 		this.connected =false
							// 	})
							if (this.clockInOrNot) {
								let pages = getCurrentPages(); //当前页面栈
								let beforePage = pages[pages.length - 2]; //指定调用页面为上个页面
								beforePage.$vm.punchTheClock() //getData 是你要调用上个页面的方法，微信小程序不需要用 $vm
								uni.navigateBack({
									delta: 1
								});
							}

							setTimeout(() => {
								uni.navigateBack({
									delta: 1
								});
							}, 2000);
						// }
					} else {
						uni.showToast({
							title: res.data.message,
							icon: "none",
							duration: 2000
						});
					}
				}).catch(err => {})
			},
			// api存储电子秤数据
			tbEquipmentData(deviceId, equipmentData, mac) {
				let _this = this,
					fdata = {
						equipmentTypeId: 1, //设备类型1:体脂秤2：血压计
						deviceId: deviceId,
						equipmentData: equipmentData,
						mac: mac,
						userId: uni.getStorageSync(global.IS_DEV?'USER_DATA_BSY_T':'USER_DATA_BSY_Z').userId
					}
				this.$api.post(global.apiUrls.tbEquipmentData, fdata)
					.then(res => {
						if (res.data.code == 1000) { //成功
						} else {
							uni.showToast({
								title: res.data.message,
								icon: "none",
								duration: 2000
							});
						}
					}).catch(err => {})
			},


			/**
			 * 获取到了实时的稳定测量数据，在连接APP的情况下，进行测量，数据会进入到这个回调
			 * @param {object} scaleData 体脂秤数据
			 */
			onGetScaleData(scaleData) {
				this.updateState("测量完成")
				// 数据返回
				console.log("称重结束", scaleData)
				console.log("发送数据", scaleData)
				// 发送请求保存到数据库中
				// let scaleData1 = scaleData;

					this.balanceData({
						equipmentData: JSON.stringify(scaleData),
						deviceId: this.deviceId,
						mac: this.mac
					})

				// this.$emit('balanceData',{
				// 	equipmentData:JSON.stringify(scaleData),
				// 	deviceId:this.deviceId,
				// 	mac:this.mac
				// })
				//  delete scaleData1.device;
				// let measureInfo = scaleData.user;

				// wx.request({
				// 	url: 'http://192.168.100.9:18602/equipment/measureResult', //仅为示例，并非真实的接口地址
				// 	method: "POST",
				// 	header: {
				// 		"Content-Type": "application/x-www-form-urlencoded",
				// 		"Authorization": 'eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOjEsInN1YiI6InVzZXIiLCJmb3VuZGVyIjpudWxsLCJyb2xlcyI6WyJTVVBFUl9BRE1JTiJdLCJleHAiOjE2MTU3ODAwNTksInV1aWQiOm51bGwsInNob3BVaWQiOm51bGwsInVzZXJuYW1lIjoiYWRtaW4ifQ.lntgpE9jPgUQzTK_jr_e0In_76tltx9MqzUQ4uEajRjwQ-my7fH8Ye9DtRRs0aScxshmNDPh6NwuvX3H8VvS-w'
				// 	},
				// 	data: {
				// 		measureResult: JSON.stringify(scaleData1),
				// 		measureInfo: JSON.stringify(measureInfo),
				// 		equipmentId: 1
				// 	},
				// 	success(res) {
				// 		console.log(res.data)
				// 	},
				// 	error(e) {
				// 		console.log(e)
				// 	}
				// })

				const report = new Report(scaleData)
				console.log(report,'4900000000000000')
				// this.realTimeWeight = scaleData.weight;
				// this.state = "paused";
				// this.score = scaleData.score.toString();
				// this.measureData = report
			},

			onStartMeasureFat() {
				console.log("开始测量体脂")
			},

			onStartMeasureHeart() {
				console.log("开始测量心率")
			},
			/**
			 * 发送请求计算测量数据失败
			 * @param {*} err
			 */
			onFetchScaleDataFail(err) {
				console.log("计算数据失败", err)
			},

			updateState(state) {
				this.bleState = state
			},

			testRequest() {
				const weight = 60
				const {
					height,
					age,
					gender,
					isSport
				} = this.data
				const birthday = new Date()
				birthday.setFullYear(birthday.getFullYear() - age)
				const user = {
					height,
					age,
					gender,
					isSport,
					birthday,
				}

				this.bleApi.fakeRequest(weight, user)
					.then((measureData) => {
						console.log(measureData,'5355555555555555555555')
						const report = new Report(measureData)
						console.log("报告数据", report)
						this.measureData = report;
						this.score = measureData.score.toString();
					})

			},
		}
	}
</script>

<style lang="scss">
	.equipmentbg {
		width: 100vw;
		min-height: 100vh;
		background: url(http://static.bsyjk.cn/equipmentbg/0DB19D05B0D1471BBCBDD70DAEDE2374.png)no-repeat;
		background-size: 100% 100%;

		.equipmenttz {
			width: 750upx;
			height: 1460upx;
			background: url(http://static.bsyjk.cn/equipmenttz/3093410BA4DF472B934E97E93D76BF03.png)no-repeat;
			background-size: 100% 100%;
			position: relative;
			color: #2EA7E0;
			text-align: center;

			.buzhou-one {
				width: 690upx;
				left: 50%;
				transform: translateX(-50%);
				font-size: 26upx;
				position: absolute;
				top: 74upx;

				.bz-text {
					font-size: 36upx;
					padding-right: 20upx;
				}
			}
		}
	}
</style>
